<template>
  <div class="all-animes-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>全部动漫</h1>
      <p>浏览所有收录的动漫作品</p>
    </div>
    
    <!-- 筛选和排序控制 -->
    <div class="filter-controls">
      <div class="filter-group">
        <label for="season">选择季度：</label>
        <select id="season" v-model="selectedSeason" @change="applyFilter">
          <option value="all">全部季度</option> 
          <option value="冬季">冬季</option>
          <option value="春季">春季</option>
          <option value="夏季">夏季</option>
          <option value="秋季">秋季</option>
        </select>
      </div>
      
      <div class="filter-group">
        <label for="year">选择年份：</label>
        <select id="year" v-model="selectedYear" @change="applyFilter">
          <option value="all">全部年份</option>
          <option v-for="year in availableYears" :key="year" :value="year">{{ year }}</option>
        </select>
      </div>
      
      <div class="filter-group">
        <label for="genre">选择类型：</label>
        <select id="genre" v-model="selectedGenre" @change="applyFilter">
          <option value="all">全部类型</option>
          <option v-for="genre in availableGenres" :key="genre" :value="genre">{{ genre }}</option>
        </select>
      </div>
      
      <div class="sort-group">
        <label for="sort">排序方式：</label>
        <select id="sort" v-model="sortBy" @change="applySort">
          <option value="rating">按评分</option>
          <option value="votes">按票数</option>
          <option value="title">按标题</option>
        </select>
      </div>
    </div>
    
    <!-- 动漫列表 -->
    <div class="animes-list">
      <StandardAnimeGrid
        :animes="allAnimes"
        :loading="loading"
        :show-pagination="true"
        :items-per-page="itemsPerPage"
        :total-pages="totalPages"
        :current-page="currentPage"
        @vote="handleVote"
        @favorite="handleFavorite"
        @show-detail="showAnimeDetail"
        @page-change="handlePageChange"
        ref="animeGrid"
      />
    </div>
    
    <!-- 动漫详情弹窗 -->
    <AnimeDetailModal 
      v-if="selectedAnime"
      :anime="selectedAnime"
      @close="closeAnimeDetail"
      @vote="handleVote"
      @favorite="handleFavorite"
    />
    
    <!-- 登录提示弹窗 -->
    <LoginPromptModal
      :show="showLoginPrompt"
      :message="loginPromptMessage"
      @close="showLoginPrompt = false"
      @login="handleLoginClick"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import StandardAnimeGrid from '../components/StandardAnimeGrid.vue'
import AnimeDetailModal from '../components/AnimeDetailModal.vue'
import LoginPromptModal from '../components/LoginPromptModal.vue'
import type { Anime } from '../types/anime'
import { addFavorite, removeFavorite, checkFavorite, batchCheckFavorites } from '../services/favoriteService'
import { isAuthenticated } from '../services/userService'
import toastService from '../services/toastService'
import { voteForAnime } from '../services/voteService'

const router = useRouter()

// 页面状态
const loading = ref(false)
const allAnimes = ref<Anime[]>([])
const selectedAnime = ref<Anime | null>(null)
const itemsPerPage = 12 // 一行四个，共三行
const currentPage = ref(1)
const totalPages = ref(1)
const totalItems = ref(0)
const animeGrid = ref<InstanceType<typeof StandardAnimeGrid> | null>(null)

// 登录提示相关状态
const showLoginPrompt = ref(false)
const loginPromptMessage = ref('')

// 筛选条件
const selectedSeason = ref('all')
const selectedYear = ref('all')
const selectedGenre = ref('all')
const sortBy = ref('rating')

// 可用的年份和类型选项
const availableYears = ref<number[]>([2024, 2023, 2022, 2021, 2020, 2019])
const availableGenres = ref<string[]>(['战斗', '热血', '奇幻', '科幻', '悬疑', '校园', '恋爱', '喜剧'])

// filteredAndSortedAnimes removed as it's not being used

// 应用筛选
const applyFilter = () => {
  // 重置到第一页
  currentPage.value = 1
  if (animeGrid.value) {
    animeGrid.value.resetToFirstPage()
  }
  loadAnimes(1, true)
}

// 应用排序
const applySort = () => {
  loadAnimes(currentPage.value)
}

// 处理页面变更
const handlePageChange = (page: number) => {
  currentPage.value = page
  loadAnimes(page)
  // 可以在这里添加页面变更时的逻辑
  console.log('切换到页面:', page)
}

// 检查登录状态的通用函数
const checkLogin = (actionType: 'vote' | 'favorite'): boolean => {
  const isLoggedIn = isAuthenticated()
  if (!isLoggedIn) {
    loginPromptMessage.value = actionType === 'vote' 
      ? '请先登录后再投票！'
      : '请先登录后再收藏！'
    showLoginPrompt.value = true
    return false
  }
  return true
}

// 处理登录按钮点击
const handleLoginClick = () => {
  router.push('/login')
}

// 处理投票
const handleVote = async (animeId: number) => {
  // 检查登录状态
  if (!checkLogin('vote')) {
    return
  }
  
  try {
    // 调用投票API
    const success = await voteForAnime(animeId)
    
    if (success) {
      // 更新本地数据的投票数
      const anime = allAnimes.value.find(a => a.id === animeId)
      if (anime) {
        anime.votes = (anime.votes || 0) + 1
      }
      toastService.success('投票成功！')
    } else {
      toastService.error('投票失败，请重试')
    }
  } catch (error) {
    console.error('投票失败:', error)
    toastService.error('投票失败，请重试')
  }
}

// 处理收藏事件
const handleFavorite = async (eventData: number | { animeId: number, isFavorited: boolean }) => {
  // 检查登录状态
  if (!checkLogin('favorite')) {
    return
  }
  
  // 处理不同格式的输入
  let animeId: number;
  let isFavorited: boolean | null = null;
  
  if (typeof eventData === 'object' && eventData !== null) {
    // 新格式 - 对象包含animeId和isFavorited
    animeId = eventData.animeId;
    isFavorited = eventData.isFavorited;
  } else {
    // 兼容旧格式 - 直接传入animeId
    animeId = Number(eventData);
  }
  
  try {
    // 首先尝试从本地anime对象获取当前收藏状态
    const anime = allAnimes.value.find(a => a.id === animeId)
    if (isFavorited === null && anime) {
      // 优先使用本地状态，避免额外的API调用
      isFavorited = anime.isFavorite || false;
    }
    
    // 如果本地没有状态，才调用API检查
    if (isFavorited === null) {
      isFavorited = await checkFavorite(animeId);
    }
    
    if (isFavorited) {
      // 取消收藏
      await removeFavorite(animeId);
      toastService.success('取消收藏成功！')
    } else {
      // 添加收藏
      await addFavorite(animeId);
      toastService.success('收藏成功！')
    }
    
    // 更新本地状态
    if (anime) {
      // isFavorited是操作前的状态，操作后状态取反
      anime.isFavorite = !isFavorited;
      if (anime.favorites !== undefined) {
        anime.favorites = isFavorited 
          ? Math.max(0, anime.favorites - 1) 
          : (anime.favorites || 0) + 1;
      }
    }
  } catch (error) {
    console.error('收藏操作失败:', error)
    toastService.error('操作失败，请重试')
  }
}

// 显示动漫详情
const showAnimeDetail = (anime: Anime) => {
  selectedAnime.value = anime
}

// 关闭动漫详情
const closeAnimeDetail = () => {
  selectedAnime.value = null
}

// 加载动漫数据
const loadAnimes = async (page: number = 1, resetFilters: boolean = false) => {
  loading.value = true
  
  try {
    // 如果重置筛选条件，则将页面重置为第一页
    if (resetFilters) {
      currentPage.value = 1
      page = 1
    }
    
    // 准备筛选参数
    const season = selectedSeason.value === 'all' ? undefined : selectedSeason.value
    const year = selectedYear.value === 'all' ? undefined : Number(selectedYear.value)
    const genre = selectedGenre.value === 'all' ? undefined : selectedGenre.value
    
    // 从animeService导入搜索方法
    const { searchAnimes } = await import('../services/animeService')
    // 调用搜索方法，传递分页和筛选参数
    const result = await searchAnimes('', page, itemsPerPage, season, year, genre, sortBy.value)
    
    // 处理返回的数据，只在必要时添加默认值
    const enhancedAnimes = (result.records || []).map((anime: Anime) => ({
      ...anime,
      // 只在字段不存在或为空时添加默认值
      year: anime.year || new Date().getFullYear(),
      season: anime.season || '未知',
      // 确保必要字段存在
      id: anime.id,
      title: anime.title || '未知标题',
      coverImageUrl: anime.coverImageUrl || '',
      rating: anime.rating || 0,
      // 默认为未收藏
      isFavorite: false
    }))
    
    allAnimes.value = enhancedAnimes
    
    // 批量检查收藏状态
    await updateFavoritesStatus(enhancedAnimes)
    currentPage.value = result.page || 1
    totalPages.value = result.totalPages || 1
    totalItems.value = result.total || 0
    loading.value = false
  } catch (error) {
    console.error('加载动漫数据失败:', error)
    loading.value = false
  }
}

// 批量更新收藏状态
  const updateFavoritesStatus = async (animesToUpdate: Anime[]) => {
    if (!animesToUpdate || animesToUpdate.length === 0) return
    
    // 检查用户是否已登录
    if (!isAuthenticated()) return // 用户未登录，不需要检查
    
    try {
      // 提取动漫ID列表
      const animeIds = animesToUpdate.map(anime => {
        return typeof anime.id === 'string' ? parseInt(anime.id) : anime.id
      })
      
      // 批量检查收藏状态
      const favoritesMap = await batchCheckFavorites(animeIds)
      
      // 更新每个动漫的收藏状态
      animesToUpdate.forEach(anime => {
        const animeId = typeof anime.id === 'string' ? parseInt(anime.id) : anime.id
        anime.isFavorite = favoritesMap[animeId] || false
      })
    } catch (error) {
      console.error('更新收藏状态失败:', error)
    }
  }

// 组件挂载时加载数据
onMounted(() => {
  loadAnimes(1)
})
</script>

<style scoped>
.all-animes-page {
  padding: 24px 0;
}

.page-header {
  text-align: center;
  margin-bottom: 40px;
  animation: fadeInUp 0.6s ease-out;
}

.filter-controls {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin-bottom: 32px;
  justify-content: center;
  padding: 0 16px;
}

.filter-group, .sort-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-group label, .sort-group label {
  font-weight: 500;
  color: #6C6C70;
}

.filter-group select, .sort-group select {
  padding: 8px 12px;
  border-radius: 8px;
  border: 1px solid #E5E5EA;
  background-color: white;
  font-size: 1rem;
  color: #1C1C1E;
  outline: none;
  cursor: pointer;
  transition: border-color 0.2s ease;
}

.filter-group select:focus, .sort-group select:focus {
  border-color: #FF69B4;
}

.animes-list {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 16px;
}

.loading, .no-results {
  text-align: center;
  padding: 64px 0;
  color: #6C6C70;
}

.anime-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 24px;
  margin-bottom: 32px;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 16px;
  margin-top: 32px;
}

.pagination-btn {
  padding: 10px 20px;
  background-color: #FF69B4;
  color: white;
  border: none;
  border-radius: 12px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
}

.pagination-btn:hover:not(:disabled) {
  background-color: #FF1493;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(255, 105, 180, 0.25);
}

.pagination-btn:disabled {
  background-color: #E5E5EA;
  color: #8E8E93;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.pagination-info {
  font-size: 1rem;
  color: #6C6C70;
  font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .filter-controls {
    flex-direction: column;
    align-items: stretch;
  }
  
  .filter-group, .sort-group {
    flex-direction: column;
    align-items: stretch;
  }
  
  .anime-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 16px;
  }
}

@media (max-width: 480px) {
  .anime-grid {
    grid-template-columns: 1fr;
  }
}
</style>